package com.chenxi.vhr.config;

import com.chenxi.vhr.bean.BaseRole;
import com.chenxi.vhr.bean.vo.MenuVo;
import com.chenxi.vhr.service.BaseMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;

import java.util.Collection;
import java.util.List;

/**
 * 根据用户的URL获取当前请求需要的角色
 * @author : zhangchenxi
 * @create : 2022-02-03
 **/
@Component
public class CustomSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {

    @Autowired
    BaseMenuService baseMenuService;

    // 处理请求地址匹配
    AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        FilterInvocation filterInvocation = (FilterInvocation) object;
        String requestUrl = filterInvocation.getRequestUrl();
        List<MenuVo> allMenu = baseMenuService.getAllMenuWithRole();
        for(MenuVo menuVo : allMenu) {
            if (antPathMatcher.match(menuVo.getUrl(), requestUrl)) {
                List<BaseRole> roleList = menuVo.getRoleList();
                String[] roleArr = new String[roleList.size()];
                for (int i = 0; i < roleList.size() ; i++) {
                    roleArr[i] = roleList.get(i).getName();
                }
                return SecurityConfig.createList(roleArr);
            }
        }
        // 没有匹配上权限，但已登录
        return SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> clazz) {
        return true;
    }
}
